import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hc_bot_pro/chat/controller.dart';

import '../common/speech/service.dart';
import '../common/service/chat/chat.dart';
import 'state.dart';

extension ControllerBot on ChatController {
  Future setUpBot() async {
    await Get.find<HCAISpeechService>().setUp();
    //refreshTherapyList
    Get.find<HCAISpeechService>().asr.onASRCompleted = (v) {
      ask(v);
    };
    Get.find<HCAISpeechService>().tts.onSayingCompleted = () {
      if (!isInteractionEnable) return;
      updateRobotStatus(HCAIBotStatus.listening);
    };

    Get.find<HCAISpeechService>().asr.onAwake = () {
      debugPrint("onAwake");
      clearConversation();
      updateRobotStatus(HCAIBotStatus.listening);
      sayHi();
    };

    Get.find<HCAISpeechService>().asr.onSleep = () {
      debugPrint("onSleep");
      updateRobotStatus(HCAIBotStatus.sleeping);
    };
    //
    Get.find<ChatService>().onData = onReceivingChat;
    Get.find<ChatService>().onDone = onReceiveChatDone;
    Get.find<ChatService>().onCancelled = onReceviceCancelled;
  }

  void updateRobotStatus(HCAIBotStatus status) {
    state.status = status;
    update(["chat"]);
  }

  void onReceivingChat(String msg) async {
    debugPrint(msg);
    say(phase: msg, isCompleted: false);

    state.chatList.last.message += msg;
    update(["chat"]);
    tableViewController.jumpTo(tableViewController.position.maxScrollExtent);
  }

  void onReceiveChatDone() {
    debugPrint("onChatDone");
    if (state.chatList.isEmpty) return;

    updateRobotStatus(HCAIBotStatus.idle);
    say(phase: "");
  }

  void onReceviceCancelled() {
    state.chatList.removeLast();
    update(["chat"]);
  }
}
